import {Hono} from "hono";
import {getThsZjMix} from "@/backend/services/ths-service";
import {memoizedKplTopMix} from "@/backend/services/kpl-service";
import {cleanName} from "@/lib/utils";
import {getSecuCurrent} from "@/backend/services/secu-service";
import {thsMixData} from "@/types";


const addLabelToThs = (labels: any, objs: any) => {
    labels.forEach((label: string) => {
        objs.forEach((o: { label: string; name: string; }) => {

            if (!o.name.startsWith('#')) {
                if (label.toLowerCase().includes(o.name.toLowerCase()) || o.name.toLowerCase().includes(label.toLowerCase())) {
                    o.name = `#${o.name}`
                }
            }
        })
    })
    return objs;
}



export const thsRouter = new Hono()
    .get('/zj/mix', async (c) => {
        const thsMix = await getThsZjMix();
        const rank_data = thsMix?.rank_data as thsMixData[] || [];
        const data = rank_data.slice(0, 5);
        const {list: kplMixList} = await memoizedKplTopMix();
        const plateLabels: string[] = kplMixList.map((p: any) => cleanName(p[1]));
        const labeled = addLabelToThs(plateLabels, data)
        // 领涨股信息
        const headerSecuCodes = labeled.map((r: { head_code: any; }) => r.head_code)
        const headerSecuCurrent = await getSecuCurrent(headerSecuCodes)
        const objHeadSecus: Record<string, any> = {}
        for (const secu of headerSecuCurrent) {
            objHeadSecus[secu.secu_code] = secu
        }
        labeled.map((r: { head_code: string | number; head_name: any; }) => {
            const headerCurrent = objHeadSecus[r.head_code]
            r.head_name = headerCurrent?.chg >= 5 ? r.head_name : ""
        })
        return c.json({data: labeled})
    })